package com.hqd.ch03.v48.context.annotation;

import com.hqd.ch03.v48.beans.factory.config.BeanDefinition;
import com.hqd.ch03.v48.context.stereotype.Component;
import com.hqd.ch03.v48.context.stereotype.Controller;
import com.hqd.ch03.v48.factory.support.GenericBeanDefinition;
import com.hqd.ch03.v48.registry.BeanDefinitionRegistry;
import org.reflections.Reflections;

import java.util.Set;

/**
 * 扫描class
 */
public class ClassPathBeanDefinitionScanner {
    private BeanDefinitionRegistry registry;

    public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) {
        this.registry = registry;
    }

    public int scan(String... basePackages) {
        int count = 0;
        for (String bp : basePackages) {
            Reflections reflections = new Reflections(bp);
            /**
             * 获取Controller和Component注解
             */
            Set<Class<?>> classes = reflections.getTypesAnnotatedWith(Controller.class);
            classes.addAll(reflections.getTypesAnnotatedWith(Component.class));
            this.registryClass(classes);
            count += classes.size();
        }
        return count;
    }

    private void registryClass(Set<Class<?>> classes) {
        for (Class<?> clazz : classes) {
            BeanDefinition bd = new GenericBeanDefinition(clazz);
            bd.setId(clazz.getSimpleName());
            bd.setScope(BeanDefinition.SCOPE_SINGLETON);
            this.registry.registerBeanDefinition(bd.getId(), bd);
        }
    }
}
